//
//  ZHZPersonalCtry.m
//  ZHZtest
//
//  Created by 李彦宏 on 2017/12/12.
//  Copyright © 2017年 LYH. All rights reserved.
//

#import "ZHZPersonalCtry.h"
#import "ZHZMyStudentCty.h"//我的学员

#import "GRClassManageVC.h"//上课管理
#import "YHGRFeeMangerVC.h"//费用管理
#import "PersonDataCtry.h"//个人资料
#import "ClassRecordCtry.h"//约课记录
#import "AboutUsPdfCtry.h"//关于我们
#import "PersonHeadView.h"//个人中心头
#import "personMdel.h"
#import "SafeViewCtry.h"//安全设置
#import "GRUserModel.h"//个人资料信息model
#import "GRUserManager.h"//个人信息管理类
#import <AVFoundation/AVFoundation.h>

#define PersonHeadViewID @"PersonHeadView"

@interface ZHZPersonalCtry ()<UITableViewDelegate,UITableViewDataSource,ChangeImgDelegate,UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (nonatomic, strong) UITableView *Persontableview;
@property (nonatomic, strong) NSMutableArray *PersonList;
@property (nonatomic, strong) GRUserModel *user;
@property (nonatomic, strong) UIImagePickerController *picker;
@property (nonatomic, strong) UIImage *img;

@end

@implementation ZHZPersonalCtry

/**
 *  个人中心数据的懒加载
 */
- (NSMutableArray *)PersonList
{
    if (_PersonList == nil) {
        // 初始化
        // 1.获得plist的全路径
        NSString *path = [[NSBundle mainBundle] pathForResource:@"PersonList.plist" ofType:nil];
        
        // 2.加载数组
        NSArray *dictArray = [NSArray arrayWithContentsOfFile:path];
        
        // 3.将dictArray里面的所有字典转成模型对象,放到新的数组中
        NSMutableArray *tgArray = [NSMutableArray array];
        for (NSDictionary *dict in dictArray) {
            // 3.1.创建模型对象
            personMdel *tg = [personMdel  personwithDict:dict];

            // 3.2.添加模型对象到数组中
            [tgArray addObject:tg];
        }

        // 4.赋值
        _PersonList = tgArray;
    }
    return _PersonList;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupTable];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    _user = [GRUserManager me];
}

    //UItableView初始化
- (void)setupTable
    {
        _Persontableview=[[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        _Persontableview.backgroundColor=[UIColor whiteColor];
        _Persontableview.showsHorizontalScrollIndicator=NO;
        _Persontableview.showsVerticalScrollIndicator=NO;
        _Persontableview.dataSource=self;
        _Persontableview.delegate=self;
    _Persontableview.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
        [self.view addSubview: self.Persontableview];
        
//        [tableView registerNib:[UINib nibWithNibName:@"HomeHotGoodsCell" bundle:nil] forCellReuseIdentifier:IdGoodsDetailAllCommentCell];
        
       [_Persontableview registerNib:[UINib nibWithNibName:@"PersonHeadView" bundle:nil] forHeaderFooterViewReuseIdentifier:PersonHeadViewID];
    }
    
#pragma -mark -----------------------------tableview datasource and delegate---------------------------------
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return   1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return   self.PersonList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 49;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 1.创建cell
    static NSString *ID = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
        cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    }
    
    // 2.取出模型
    personMdel *person=self.PersonList[indexPath.row];
    cell.textLabel.text=person.list;
    cell.imageView.image=[UIImage imageNamed:person.image];


    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.Persontableview deselectRowAtIndexPath:indexPath animated:YES];
    UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath];
    
    switch (indexPath.row) {
        case 0:{
            PersonDataCtry *vc0=[[PersonDataCtry alloc]init];
            [self.navigationController pushViewController:vc0 animated:YES];
            break;
        }
        case 1:{
            ZHZMyStudentCty *vc1 = [[ZHZMyStudentCty alloc] init];
            vc1.title=@"我的学员";
            [self.navigationController pushViewController:vc1 animated:YES];
            
            NSLog(@"--点击啦第2行--");
            
            break;
        }case 2:{
            
            GRClassManageVC *vc2=[[GRClassManageVC alloc]init];
            vc2.title=@"上课管理";
            [self.navigationController pushViewController:vc2 animated:YES];
            break;
        }case 3:{
            //费用管理
            YHGRFeeMangerVC *vc3=[[YHGRFeeMangerVC alloc]init];
            vc3.title=@"费用管理";
            [self.navigationController pushViewController:vc3 animated:YES];
            break;
        }
            
        case 4:{
            //约课记录
            ClassRecordCtry *vc3=[[ClassRecordCtry alloc]init];
            vc3.title=@"约课记录";
            [self.navigationController pushViewController:vc3 animated:YES];
            break;
        }
        case 5:{
            NSLog(@"--关于我们--");
            AboutUsPdfCtry *AboutUs=[[AboutUsPdfCtry alloc] init];
            AboutUs.title=@"公司介绍";
            //   GRAboutVC *AboutUs = [[GRAboutVC alloc]init];
            [self.navigationController pushViewController:AboutUs animated:YES];
            break;
            
        }
        case 6:{
            //安全设置
            SafeViewCtry *vc4 = [[SafeViewCtry alloc] init];
            
            [self.navigationController pushViewController:vc4 animated:YES];
            NSLog(@"cell=%@",cell);
            break;
        }
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 180;
}

#pragma -mark 头部的内容
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{

    PersonHeadView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:PersonHeadViewID];
    header.GraduteName.text=_user.name;
    header.delegate = self;
    if (self.img == nil) {
        NSString *imgUrl = [NSString stringWithFormat:@"%@%@",ImageBaseURL,[[NSUserDefaults standardUserDefaults] objectForKey:@"grpic"]];
        [header.txImg sd_setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:[UIImage imageNamed:@"头像"]];
    }else{
        header.txImg.image = self.img;
    }
    
    return header;

}

-(void)changeImage:(UITapGestureRecognizer *)sender{
    __block typeof (self) weak_self = self;
    
    _picker = [[UIImagePickerController alloc] init];
    _picker.delegate = self;
    _picker.allowsEditing = YES;
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请选择图片"
                                                                             message:@""
                                                                      preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {}];
    UIAlertAction* fromPhotoAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault                                                                 handler:^(UIAlertAction * action) {
        weak_self.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [weak_self presentViewController:weak_self.picker animated:YES completion:nil];
        NSLog(@"从相册选择");
    }];
    UIAlertAction* fromCameraAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault                                                             handler:^(UIAlertAction * action) {
        NSLog(@"相机");
        
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if(! [UIImagePickerController isSourceTypeAvailable:sourceType]){
            NSString *tips = @"相机不可用";
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:tips preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                NSLog(@"取消");
            }];
            UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                NSLog(@"确定");
            }];
            [alertController addAction:cancelAction];
            [alertController addAction:otherAction];
            [self presentViewController:alertController animated:YES completion:nil];
            return;
        }
        _picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:_picker animated:YES completion:nil];
        if (![self getCameraRecordPermisson]) {
            NSString *tips = @"请在iPhone的“设置-隐私-相机”中允许访问相机";
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:tips preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                NSLog(@"取消");
            }];
            UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                NSLog(@"确定");
            }];
            [alertController addAction:cancelAction];
            [alertController addAction:otherAction];
            [self presentViewController:alertController animated:YES completion:nil];
            
        }
        
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:fromCameraAction];
    [alertController addAction:fromPhotoAction];
    [self presentViewController:alertController animated:YES completion:nil];
    
    
    
}

#pragma mark UIImagePickerControllerDelegate
//选择图或者拍照后的回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *orignalImage = [info objectForKey:UIImagePickerControllerOriginalImage];//原图
    UIImage *editedImage = [info objectForKey:UIImagePickerControllerEditedImage];//编辑后的图片
    self.img = editedImage;
    [self.Persontableview reloadData];
    // 拍照后保存原图片到相册中
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera && orignalImage) {
        UIImageWriteToSavedPhotosAlbum(orignalImage, self, nil, NULL);
    }
    //上传照片
    [picker dismissViewControllerAnimated:YES completion:^{
        if (editedImage) {
            [self doUploadPhoto:editedImage];
        }
    }];
}

-(void)doUploadPhoto:(UIImage *)img{
    
    NSDictionary *dict=@{
                         @"gid" : Gid,
                         @"gpass" : Gpassword,
                         };
    NSData *fileData = UIImageJPEGRepresentation(img, 1.0);
    [[AFNetworkTool shareManager]upLoadSinglePictureWithUrl:GR_Headimg parameters:dict fileData:fileData progerss:^(NSProgress * _Nullable progress) {
          NSLog(@"--uploadProgress--%@", progress);
    } success:^(id  _Nullable json) {
          NSLog(@"%@", json);
        NSUserDefaults *userDefaults =[NSUserDefaults standardUserDefaults];
        [userDefaults removeObjectForKey:@"grpic"];
        [userDefaults setObject:json[@"pic"] forKey:@"grpic"];
        [self.Persontableview reloadData];
    } failure:^(NSError * _Nullable error) {
          NSLog(@"%@", error);
    }];
}
//获得设备是否有访问相机权限
-(BOOL)getCameraRecordPermisson
{
    NSString * mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied)
    {
        return NO;
    }
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
